package root.electronclass.electronclass.home.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.graphics.toColorInt
import androidx.core.view.forEachIndexed
import root.electronclass.electronclass.R
import root.electronclass.electronclass.databinding.HomeTabItemBinding

class TabIndicator : LinearLayoutCompat {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, style: Int) : super(context, attrs, style) {
        initView()
    }

    private lateinit var list: List<String>

    lateinit var onTabChangedListener: OnTabChangedListener

    private var curIndex: Int = 0

    private fun initView() {
        setBackgroundResource(R.drawable.bg_home_tab_list)
        orientation = HORIZONTAL
    }

    fun initData(list: List<String>) {
        this.list = list
        this.list.mapIndexed { index, it ->
            val view = inflate(context, R.layout.home_tab_item, null)
            val binding = HomeTabItemBinding.bind(view)
            binding.tvTabTitle.text = it
            binding.root.setOnClickListener {
                setIndex(index)
                onTabChangedListener.onChanged(index)
            }
            addView(view, LayoutParams.WRAP_CONTENT, 32)
        }

        setIndex(curIndex)
    }

    fun setIndex(index: Int) {
        curIndex = index
        forEachIndexed { i: Int, view: View ->
            var tvTitle = view.findViewById<TextView>(R.id.tvTabTitle)
            if (i == curIndex) {
                tvTitle.setBackgroundResource(R.drawable.bg_home_tab_item)
                tvTitle.setTextColor(resources.getColor(R.color.c_white, null))
            } else {
                tvTitle.background = null
                tvTitle.setTextColor("#FF19C5FF".toColorInt())
            }
        }
    }


    interface OnTabChangedListener {
        fun onChanged(index: Int)
    }
}